#!/bin/env python
# -*- coding: utf-8 -*-

import pygtk 
pygtk.require('2.0') 
import gtk 
from random import choice
import os

class LongText(object):
    def __init__(self, content=u'', generation=4, max_length=1000):
        assert(generation>1)
        assert(generation<=len(content))

        # convert content to unicode if necessary
        if type(content) != type(u''):
            try:
                content = unicode(content,'utf-8')
            except:
                content = unicode(content,'latin-1','replace')

        if content[-1] == u'\n':
            sep = u''
        else:
            sep = u'\n'
        self.content = content + sep + content[:generation]
        self.generation=generation
        self.max_length=max_length
    def generate(self):
        # start with the first letters of a random paragraph
        result = choice( [x for x in self.content.split('\n') if len(x) > self.generation] )[:self.generation-1]
        current = result
        while len(result) < self.max_length:
            bits = [x[0] for x in self.content.split(current) if x!= '' ][1:]
            newchar = choice(bits)
            current = current[1:] + newchar
            result += newchar

        # try to finish with a meaningful sentence ending
        newlen = max(result.rfind('.'), result.rfind('!'), result.rfind('?'))
        if newlen > self.max_length * 0.8:
            result = result[:newlen+1]
        return result

class FiWaGe(object): 

    def __init__(self): 
        self.statusicon = gtk.StatusIcon() 
        self.statusicon.set_from_stock(gtk.STOCK_ABOUT) 
        self.statusicon.set_visible(True) 
        self.statusicon.set_tooltip("FiWaGe") 

        mainmenu = gtk.Menu() 
        fiwagedir = 'textfiles/'
        for fname in os.listdir(fiwagedir):
            mainmenuitem = gtk.MenuItem('%s' % fname.replace('_','-')) 
            submenu = gtk.Menu()
            for maxlen in (20,50,100,500,1000,10000):
                submenuitem = gtk.MenuItem('%i characters' % maxlen) 
                submenuitem.max_length= maxlen
                submenuitem.originaltext = file(fiwagedir + fname).read()
                submenuitem.generation = 4
                submenuitem.connect('activate', self.generate, self.statusicon) 
                submenu.append(submenuitem) 
            mainmenuitem.set_submenu(submenu)
            mainmenu.append(mainmenuitem)

        mainmenu.append(gtk.SeparatorMenuItem())
        quitmenuitem = gtk.ImageMenuItem(gtk.STOCK_QUIT) 
        quitmenuitem.connect('activate', self.do_quit, self.statusicon) 
        mainmenu.append(quitmenuitem) 

        self.statusicon.connect('popup-menu', self.do_menu, mainmenu) 
        self.statusicon.set_visible(1) 

        gtk.main() 

    def generate(self, widget, event, data=None): 
        txt = LongText(widget.originaltext, generation=widget.generation,
                max_length=widget.max_length).generate()

        clipboard = gtk.clipboard_get() # ctrl-c/v clipboard
        clipboard.set_text(txt)
        clipboard.store()
        os.popen('xsel', 'wb').write(txt) # middleclick clipboard

#        window = gtk.Window(gtk.WINDOW_TOPLEVEL) 
#        window.set_border_width(10) 
#
#        button = gtk.Button("Hello World") 
#        button.connect_object("clicked", gtk.Widget.destroy, window) 
#
#        window.add(button) 
#        button.show() 
#        window.show() 

    def do_quit(self, widget, data = None): 
        gtk.main_quit() 

    def do_menu(self, widget, button, time, data=None): 
        if button == 3: 
            if data: 
                data.show_all() 
                data.popup(None, None, gtk.status_icon_position_menu, 3, time, self.statusicon) 

if __name__ == "__main__": 
    FiWaGe()

